﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml.Serialization;

namespace Daneas.Utility.Universals
{
    /// <summary>
    /// 序列化和反序列化
    /// </summary>
    public class SerializaTool
    {
        /// <summary>
        /// 二进制序列化对象
        /// </summary>
        /// <param name="obj"></param>
        public static string BinarySerialize(object obj)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();

            formatter.TypeFormat = FormatterTypeStyle.TypesAlways;
            formatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
            formatter.Serialize(ms, obj);

            byte[] x = ms.ToArray();
            ms.Close();

            return Convert.ToBase64String(x);
        }

        /// <summary>
        /// 二进制反序列化
        /// </summary>
        /// <param name="fileName"></param>
        public static T BinaryDeserialize<T>(string serString)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            byte[] x = Convert.FromBase64String(serString);

            MemoryStream ms = new MemoryStream(x);
            ms.Position = 0;
            ms.Seek(0, SeekOrigin.Begin);

            return (T)formatter.Deserialize(ms);
        }

        /// <summary>
        /// 二进制序列化对象
        /// </summary>
        /// <param name="obj"></param>
        public static string SOAPSerialize(object obj)
        {
            Stream stream = null;

            SoapFormatter formater = new SoapFormatter();
            formater.Serialize(stream, obj);

            return stream.ToString();

        }

        /// <summary>
        /// 二进制反序列化
        /// </summary>
        /// <param name="fileName"></param>
        public static T SOAPDeserialize<T>(string serString)
        {
            StreamReader sr = new StreamReader(serString);
            Stream stream = sr.BaseStream;

            SoapFormatter formater = new SoapFormatter();
            return (T)formater.Deserialize(stream);
        }

        /// <summary>
        /// XML序列化
        /// </summary>
        /// <param name="obj"></param>
        public static string XMLSerialize<T>(T obj)
        {
            StringWriter sw = new StringWriter();
            XmlSerializer xmlSer = new XmlSerializer(obj.GetType());
            xmlSer.Serialize(sw, obj);

            return sw.ToString();
        }

        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <param name="fileName"></param>
        public static T XMLDeserialize<T>(string serString)
        {
            if (string.IsNullOrWhiteSpace(serString))
            {
                return default(T);
            }

            StringReader sr = new StringReader(serString);
            XmlSerializer xmlSer = new XmlSerializer(typeof(T));
            return (T)xmlSer.Deserialize(sr);
        }

        /// <summary>
        /// JSON序列化
        /// </summary>
        public static string JsonSerializer<T>(T t)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();

            return ser.Serialize(t);

        }

        /// <summary>
        /// JSON反序列化
        /// </summary>
        public static T JsonDeserialize<T>(string jsonString)
        {
            JavaScriptSerializer ser = new JavaScriptSerializer();

            T t = ser.Deserialize<T>(jsonString);

            return t;
        }

        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns> 
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, object>>(jsonText);
        }

        /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJSON(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Serialize(obj);
            }
            catch (Exception ex)
            {

                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }

        /// <summary> 
        /// 数据表转键值对集合 www.2cto.com  
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }

        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="dataSet">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();

            foreach (DataTable dt in ds.Tables)
            {
                result.Add(dt.TableName, DataTableToList(dt));
            }

            return result;
        }

        /// <summary> 
        /// JSON文本转对象,泛型方法 
        /// </summary> 
        /// <typeparam name="T">类型</typeparam> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>指定类型的对象</returns> 
        public static T JSONToObject<T>(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Deserialize<T>(jsonText);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        }

    }
}
